package com.greyshark.bledemo.ui

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.os.Build
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.greyshark.bledemo.base.BaseActivity
import com.greyshark.bledemo.base.SimpleAdapter
import com.greyshark.bledemo.databinding.ActivityScanBinding
import com.greyshark.bledemo.databinding.LayoutItemDeviceBinding
import com.greyshark.bledemo.tools.AppSystemTools
import com.greyshark.bledemo.tools.PermissionTools
import com.greyshark.lib.bluetooth.ControlCenterClient
import com.greyshark.lib.bluetooth.entity.ScanDeviceEntity
import com.greyshark.lib.bluetooth.scan.MyBleScanState
import com.greyshark.lib.bluetooth.scan.SimpleScanCallback
import com.greyshark.lib.bluetooth.scan.scanner.ScanResult
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.launch

class ScanActivity : BaseActivity<ActivityScanBinding>(
  inflate = ActivityScanBinding::inflate
), View.OnClickListener {

  private val dataList = arrayListOf<ScanDeviceEntity>()
  private val macList = arrayListOf<String>()

  private val simpleScanCallback = object : SimpleScanCallback {
    override fun onBleScanStop(scanState: MyBleScanState?) {}

    override fun onBleScan(
      device: BluetoothDevice?,
      rssi: Int,
      scanRecord: ByteArray?
    ) {
    }

    @SuppressLint("MissingPermission")
    override fun onBleScan(results: List<ScanResult?>) {
      for (item in results) {
        LogUtils.i("device name=${item?.device?.name}")
        LogUtils.i("device address=${item?.device?.address}")
        LogUtils.i("device rssi=${item?.rssi}")

        item?.device?.address?.let {
          if (macList.contains(it)){
            return
          }
          macList.add(it)
        }

        dataList.add(
          ScanDeviceEntity(
            device = item?.device,
            name = item?.device?.name.toString(),
            address = item?.device?.address.toString(),
            rssi = item?.rssi.toString()
          )
        )
        binding.rvDevice.adapter?.notifyDataSetChanged()
      }
    }

  }

  @SuppressLint("MissingPermission")
  override fun onClick(v: View?) {
    when (v?.id) {
      binding.ivStartScan.id -> {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
          if (!PermissionTools.checkPermissions(permissions = (PermissionTools.PERMISSION_BLE12 + PermissionTools.PERMISSION_GROUP_LOCATION))) {
            PermissionTools.requestPermissions(
              perName = "",
              permissions = (PermissionTools.PERMISSION_BLE12 + PermissionTools.PERMISSION_GROUP_LOCATION)
            ) {
              binding.ivStartScan.callOnClick()
            }
            return
          }
        }
        if (!PermissionTools.checkPermissions(permissions = PermissionTools.PERMISSION_GROUP_LOCATION)) {
          PermissionTools.requestPermissions(
            perName = "",
            permissions = PermissionTools.PERMISSION_GROUP_LOCATION
          ) {
            binding.ivStartScan.callOnClick()
          }
          return
        }


        if (!AppSystemTools.isGPSOpen()) {
          AppSystemTools.enableGPS()
          return
        }

        if (!AppSystemTools.isBluetoothOpen()) {
          AppSystemTools.enableBluetooth()
          return
        }

        lifecycleScope.launch {
          ControlCenterClient.instance.startScan(30_000L)
            .catch { it ->
              LogUtils.i("startScan catch error: ${it.message}")
            }.onCompletion { it ->
              LogUtils.i("startScan onCompletion error: ${it?.message}")
            }.collect { it ->
              LogUtils.i("device name=${it.device?.name}, address=${it.device?.address}, rssi=${it.rssi}")
              if (it.device?.name.isNullOrEmpty()) return@collect
              it.device?.address?.let {
                if (macList.contains(it)){
                  return@collect
                }
                macList.add(it)
              }
              dataList.add(
                ScanDeviceEntity(
                  device = it.device,
                  name = it.device?.name.toString(),
                  address = it.device?.address.toString(),
                  rssi = it.rssi
                )
              )
              binding.rvDevice.adapter?.notifyDataSetChanged()
            }
        }
      }

      binding.ivStopScan.id -> {
        ControlCenterClient.instance.stopScan()
      }

      else -> {}
    }
  }

  override fun initUI() {
    super.initUI()
    setViewsClickListener(this, binding.ivStartScan, binding.ivStopScan)
    binding.rvDevice.apply {
      layoutManager = LinearLayoutManager(this@ScanActivity)
      adapter = dataAdapter
    }
  }

  override fun initData() {
    super.initData()
  }

  private val dataAdapter = object : SimpleAdapter<ScanDeviceEntity, LayoutItemDeviceBinding>(
    data = dataList,
    inflater = LayoutItemDeviceBinding::inflate,
  ) {

    override fun onBindData(
      binding: LayoutItemDeviceBinding?,
      t: ScanDeviceEntity,
      position: Int
    ) {
      binding?.apply {
        tvName.text = t.name
        tvMac.text = t.address
        tvRssi.text = t.rssi
      }
      binding?.root?.setOnClickListener {
        ControlCenterClient.instance.stopScan()
        val intent = Intent(this@ScanActivity, FunctionActivity::class.java)
        intent.putExtra("BLE_NAME", t.name)
        intent.putExtra("BLE_ADDRESS", t.address)
        intent.putExtra("BLE_DEVICE", t.device)
        startActivity(intent)
      }
    }

  }
}